<template>
  <el-dialog
    v-model="state.visible"
    title="保存为我的资源"
    class="saveword-dialog"
    width="720"
    append-to-body
    :before-close="close"
  >
    <el-form v-loading="submitLoading" ref="ruleFormRef" :model="state.editData" :rules="rules" label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="state.editData.name" class="inputWidth" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="类别" prop="fileType">
        <el-input v-model="state.editData.fileType" placeholder="" class="inputWidth" style="display: none" />
        <div class="leibie-con">
          <div
            v-for="(v, k) in state.fileTypeList"
            :key="k"
            :class="`f-t-l ${state.editData.fileType === v.id ? 'f-t-c' : ''}`"
            @click="zjCheck(v.id)"
          >
            {{ v.title }}
          </div>
          <div :class="`f-t-l ${state.editData.fileType === '' ? 'f-t-c' : ''}`" @click="zjCheck('')">其它</div>
        </div>
      </el-form-item>

      <el-form-item label="教材" prop="">
        <span class="jiaocai">{{ state.values[1] }}</span>
        <span class="jiaocai">{{ state.values[2] }}</span>
        <el-select v-model="state.version" class="jiaocai" placeholder="请选择出版社" @change="getChapter">
          <el-option v-for="item in state.versionList" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
        <el-select v-model="state.volume" class="jiaocai" placeholder="请选择分册" @change="getChapter">
          <el-option v-for="item in state.volumeList" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item label="章节" prop="chapter">
        <el-cascader
          v-model="state.editData.chapterId"
          :options="state.chapterList"
          :props="{ checkStrictly: false, emitPath: false }"
          clearable
          class="inputWidth"
          style="width: 100%"
        />
      </el-form-item>
      <div class="dialog-footer">
        <div class="cancel" @click="close">取消</div>
        <div class="save" @click="onOk">确定</div>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'; 
import _ from 'lodash';
import { getTree, getStorage } from '@/utils/index';
import type { FormInstance, FormRules } from 'element-plus';
import { fileTypeGet, getCommentCache, chapterGet, strToFile } from '@/services/chat';
import { createFileSetMarkDown, userRes } from '../../../services/chat';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['saves']);
const props = defineProps({
  item: {
    type: Object,
  },
  prompts: {
    type: Array,
    default: () => [],
  },
  logExt: {
    type: String,
    default: () => '{}',
  },
  saveStr: {
    type: String,
    default: '',
  },
});

const ruleFormRef = ref<FormInstance>() as any;
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  fileType: [{ required: true, message: '请选择文件类别', trigger: 'change' }],
  fileSource: [{ required: true, message: '请选择来源', trigger: 'change' }],
});

const state = reactive({
  visible: false,
  editData: {} as any,
  fileTypeList: [] as any, // 文件类型
  sourceList: [] as any, // 资源
  chapterList: [] as any, // 章节
  gradeList: [] as any,
  subjectList: [] as any,
  versionList: [] as any,
  volumeList: [] as any,
  grade: '3',
  subject: 'a',
  version: '',
  volume: '',
  values: {} as any,
});

const show = () => {
  state.visible = true;
  // 获取列表
  resTypeGet();
};

defineExpose({
  show,
});

onMounted(async () => {
  if (props.prompts[1]) {
    state.values = props.prompts;
  } else {
    try {
      state.values = JSON.parse(props.logExt).values;
    } catch (error) {
      console.log('error ===> ', error, props);
    }
  }
});
const resTypeGet = async () => {
  const { fileType = [], sourceList = [] } = await fileTypeGet();
  state.fileTypeList = fileType;
  state.sourceList = sourceList;
  // state.editData.fileSource = (_.head(sourceList) as any).code || '';
  // 默认我的资源
  state.editData.fileSource = '1';
  const v = await getCommentCache({ term: 'common_paper' });
  state.gradeList = (v[2] as any).data || [];
  state.subjectList = (v[3] as any).data || [];
  state.versionList = (v[4] as any).data || [];
  state.volumeList = (v[5] as any).data || [];
  // 根据选的值，筛选出code值
  // state.values,0课程或知识点，1年级，2科目
  const { code: gradeCode } = _.find(state.gradeList, { name: state.values[1] }) || {};
  state.grade = gradeCode;
  const { code: subjectCode } = _.find(state.subjectList, { name: state.values[2] }) || {};
  state.subject = subjectCode;
};
const zjCheck = (id: string) => {
  state.editData = { ...state.editData, fileType: id };
};
// 获取章节
const getChapter = async () => {
  if (state.grade && state.subject && state.version && state.volume) {
    const args = {
      grade: state.grade,
      subject: state.subject,
      publishers: state.version,
      fascicule: state.volume,
      status: '1',
      bookVersion: 'v1',
    };
    const { data } = await chapterGet(args);
    // 筛选的是哪个知识点
    const { id = '' } = _.find(data, { title: state.values[0] }) || {};
    state.editData.chapterId = id;
    const tableData = _.map(_.sortBy(data, 'sortNum'), v => ({
      ...v,
      pid: v.pid === '0' ? null : v.pid,
      name: v.title,
    })) as any;
    state.chapterList = getTree(tableData) || [];
  }
};
const close = () => {
  ruleFormRef.value.resetFields();
  state.visible = false;
  emit('saves');
};
const onOk = () => {
  ruleFormRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      // 外层判断不展示弹窗
      addMyWorker();
    }
  });
};

const forMatQuestion = computed(() => {
  let raw = props.saveStr;

  // 确保是字符串
  if (typeof raw !== 'string') return [];

  // 清洗伪 JSON 字符串 => 合法 JSON 字符串
  raw = raw
    .trim()
    // 替换属性名未加引号
    .replace(/([{,]\s*)([a-zA-Z0-9_]+)\s*:/g, '$1"$2":')
    // 替换值单引号为双引号
    .replace(/:\s*'([^']*?)'/g, ': "$1"')
    // 替换数组中的单引号
    .replace(/'\s*,\s*'/g, '", "')
    .replace(/\[\s*'/g, '["')
    .replace(/'\s*\]/g, '"]')
    // ✅ 移除对象或数组末尾多余的逗号：包括 "],", "},"
    .replace(/,\s*([\]}])/g, '$1');

  try {
    return JSON.parse(raw);
  } catch (e: any) {
    console.log('raw==========> ', raw);
    console.error('❌ 无法解析 questions 字符串:', e.message);
    return [];
  }
});

const convertToMarkdown = (questionsData: any) => {
  return questionsData
    .map((q: any, index: any) => {
      const title = `#### ${index + 1}. ${q.stem}`;
      const options = q.options.map((opt: any) => `- [ ] ${opt}`);
      return `${title}\n${options.join('\n')}`;
    })
    .join('\n\n');
};
const submitLoading = ref(false);
const addMyWorker = () => {
  submitLoading.value = true;
  const markdownData = convertToMarkdown(forMatQuestion.value);
  const userId = getStorage('userId') || '';
  const { grade, subject, version, volume } = state;
  const args = { id: userId, grade, subject, version, volume };
  // 上传成为文件
  const name = `${state.values[1]}-${state.values[2]}-AI生题-${new Date().getTime()}.doc`;
  createFileSetMarkDown({
    name,
    data: markdownData,
  }).then(async res => {
    // console.log('res ===============> ', res);
    if (!res.err) {
      let id;
      // 保存到我的资源
      const data = {
        userId,
        grade,
        subject,
        name,
        version,
        volume,
        filePath: res.filePath,
        fileType: 'f',
        fileEtag: res.etag,
        fileSize: res.fileSize,
      };
      // 需要保存到我的资源
      id = await userRes(data);
      // 关闭
      let filePath = 'https://file.hnszjc.com/' + res.filePath;
      const pItem = { name: name, filePath, classify: 'f', id };
      ElMessage.success('操作成功');
      setTimeout(() => {
        submitLoading.value = false;
        close();
      }, 1000);
    } else {
      ElMessage.error('添加试题错误,请刷新后重试！');
      submitLoading.value = false;
    }
  });
};
</script>

<style lang="scss" scoped>
.saveword-dialog {
  .inputWidth {
    width: 100%;
  }
  .jiaocai {
    margin-right: 16px;
  }
  .leibie-con {
    display: flex;
    flex-wrap: wrap;
    grid-gap: 8px;
  }
  .f-t-l {
    display: inline-block;
    padding: 4px 14px;
    // margin-right: 8px;
    border: 1px solid #eee;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    color: #6a6a6a;
    line-height: 20px;
  }
  .f-t-c {
    padding: 4px 14px;
    border: 1px solid #ff8500;
    background: rgba(255, 133, 0, 0.1);
    color: #ff8500;
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    .cancel {
      width: 81px;
      height: 32px;
      background: #f9f9f9;
      border-radius: 16px;
      font-size: 14px;
      color: #6a6a6a;
      text-align: center;
      line-height: 32px;
      cursor: pointer;
    }
    .save {
      width: 81px;
      height: 32px;
      background: #ff8500;
      border-radius: 16px;
      font-size: 14px;
      color: #fff;
      text-align: center;
      line-height: 32px;
      cursor: pointer;
      margin-left: 16px;
    }
  }
}
</style>
<style lang="scss">
.saveword-dialog {
  border-radius: 8px;
  .el-select .el-input__wrapper {
    // background: rgba(60, 126, 255, 0.05) !important;
    // border: 1px solid #dee8f9 !important;
    height: 32px !important;
    box-sizing: border-box;

    .el-input__inner {
      // color: #3c7eff !important;
      height: 32px !important;
    }
  }
  .el-select .el-input .el-select__caret {
    // color: #3c7eff !important;
  }
  .el-textarea__inner {
    // color: #375275 !important;
  }

  input {
    // 解决输入框第一次点击闪烁问题
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0) !important;
  }

  .el-select:hover .el-input__wrapper {
    // border: 1px solid #3c7eff !important;
    // box-shadow: none !important;
    box-sizing: border-box;
    // padding: 1px 14px;
  }

  .el-select .el-input__wrapper.is-focus {
    // border: 1px solid #dee8f9 !important;
    // box-shadow: none !important;
  }
  // =======================================================
  .el-range-editor--small .el-range-separator {
    line-height: 32px !important;
  }
  .el-cascader-node.in-active-path,
  .el-cascader-node.is-active,
  .el-cascader-node.is-selectable.in-checked-path {
    color: #fc8b09;
  }
  .el-cascader-node:hover {
    background-color: rgba(252, 139, 9, 0.1);
    color: rgba(252, 139, 9);
  }
  .el-radio__input.is-checked .el-radio__inner {
    border-color: #fc8b09;
    background: #fc8b09;
  }
  .el-radio__inner:hover {
    border-color: #fc8b09;
  }
}
</style>
